﻿using UnityEngine;
using UnityEngine.UI;

public class RenderTextureFlipper : MonoBehaviour
{
    // 原始的RenderTexture
    public RenderTexture sourceTexture;

    // 翻转后的RenderTexture
    public RenderTexture flippedTexture;

    // 用来存储像素数据的临时Texture2D
    private Texture2D tempTexture;

    void Start()
    {
        sourceTexture = GetComponent<RawImage>().texture as RenderTexture;
        
        // 初始化临时Texture2D
        if (sourceTexture != null)
        {
            tempTexture = new Texture2D(sourceTexture.width, sourceTexture.height, TextureFormat.RGBA32, false);
            
            // 创建翻转后的RenderTexture
            flippedTexture = new RenderTexture(sourceTexture.width, sourceTexture.height, 0);

            // 翻转X和/或Y轴
            FlipTexture(sourceTexture, flippedTexture, true, true);

            // 设置RawImage的Texture为翻转后的RenderTexture
            GetComponent<RawImage>().texture = flippedTexture;
        }
        else
        {
            Debug.LogError("No RenderTexture found on RawImage.");
        }
    }
    
    void FlipTexture(RenderTexture src, RenderTexture dest, bool flipX, bool flipY)
    {
        // 将原始RenderTexture的数据拷贝到临时Texture2D
        RenderTexture.active = src;
        tempTexture.ReadPixels(new Rect(0, 0, src.width, src.height), 0, 0);
        tempTexture.Apply();
        
        // 获取像素数据
        Color[] pixels = tempTexture.GetPixels();
        
        // 翻转后的像素数据
        Color[] flippedPixels = new Color[pixels.Length];

        int width = src.width;
        int height = src.height;
        
        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                int newX = flipX ? (width - 1 - x) : x;
                int newY = flipY ? (height - 1 - y) : y;
                
                flippedPixels[newY * width + newX] = pixels[y * width + x];
            }
        }
        
        // 设置翻转后的像素数据到临时Texture2D
        tempTexture.SetPixels(flippedPixels);
        tempTexture.Apply();
        
        // 将临时Texture2D的数据拷贝到目标RenderTexture
        RenderTexture.active = dest;
        Graphics.Blit(tempTexture, dest);
        RenderTexture.active = null;
    }
}
